package com.zhenyi.jiahua.index.admin;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jiahua.common.model.JhChannel;
import com.jiahua.common.model.JhCourse;
import com.jiahua.common.model.JhSchool;
import com.jiahua.common.model.JhStaff;
import com.jiahua.common.model.JhStudent;
import com.utils.PathUtils;
import com.zhenyi.jiahua.index.JHController;
import com.zhenyi.jiahua.interceptor.SelfClientInterceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * 学生模块
 * 
 * @author cen
 *
 */
public class StudentController extends JHController {

	public void search() {
		String keyword = getPara("keyword");
		Kv kv = Kv.create();
		// kv.set("status", 1);
		// kv.set("type", 1);
		if (StrKit.notBlank(keyword)) {
			kv.set("search", "%" + keyword + "%");
			kv.set("searchMobile", "%" + keyword + "%");
			// LogKit.info("keyword: " + keyword);
		}
		String tag = getPara("tag");
		if (StrKit.notBlank(tag)) {
			kv.set("tag", tag);
		}
		JhStaff staff = getStaff();
		Page<Record> pages = JhStudent.dao.getStudents(staff, kv, getPage(), PAGE_SIZE);
		renderPage(pages);
	}

	public void checkMobile() {
		String mobile = getPara("mobile");
		if (StrKit.isBlank(mobile)) {
			renderFailure("请输入电话号码");
			return;
		}
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHCheckMobile", mobile);
		List<Record> items = Db.use("jiahua").find(sqlPara);
		if (items.size() > 0) {
			renderFailure("号码已存在");
		} else {
			renderSuccess();
		}
	}

	/**
	 * 下载学生信息
	 * 
	 * @param kv
	 * @Time 2018年11月24日 上午1:06:24
	 */
	private void download(Kv kv) {
		kv.set("dl", 1);
		kv.set("page", null);
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHStudents", kv);
		List<Record> items = Db.use("jiahua").find(sqlPara);
		ArrayList<Map<String, Object>> rows = new ArrayList<>();
		for (Record record : items) {
			// 名字，级别，电话，总金额，已交金额，总课时，已上课时，剩余课时，是否有续费，延期，休学与终止
			Map<String, Object> row = new LinkedHashMap<>();
			row.put("姓名", record.getStr("name"));
			row.put("级别", record.getStr("tag"));
			row.put("电话", record.getStr("mobile"));
			row.put("总金额", "");
			String contractPriceStr = record.getStr("contractPrice");
			Integer contractPrice = 0;
			if (StrKit.notBlank(contractPriceStr)) {
				try {
					contractPrice = Integer.parseInt(contractPriceStr);
					row.put("总金额", contractPrice);
				} catch (Exception e) {
				}
			}
			row.put("已交金额", "");
			row.put("分期时长", record.getInt("term"));
			// row.put("总课时", "");
			row.put("已上课时", record.getInt("onClassCourseCount"));
			row.put("剩余课时", record.getInt("coreCourseLeft"));
			row.put("合同性质", record.getStr("contractMode"));
			row.put("合同时间(起)", record.getDate("contractStartDate"));
			row.put("合同时间(止)", record.getDate("contractEndDate"));
			row.put("延期时间(起)", record.getDate("delayDateStart"));
			row.put("延期时间(止)", record.getDate("delayDateEnd"));
			row.put("延期原因", record.getStr("delayReason"));
			row.put("备注", record.getStr("finMark"));
			Integer contractType = record.getInt("contractType");
			if (contractType != null) {
				if (contractType.equals(0)) {
					String allPay = record.getStr("allPay");
					row.put("已交金额", allPay);
				} else if (contractType.equals(1)) {
					Integer remainToPay = 0;
					try {
						remainToPay = Integer.parseInt(record.getStr("remainToPay"));
					} catch (Exception e) {
					}
					Integer value = contractPrice - remainToPay;
					if (value <= 0) {
						value = 0;
					}
					row.put("已交金额", value == 0 ? "" : value);
				} else if (contractType.equals(2)) {
					String allPay = record.getStr("allPay");
					row.put("已交金额", allPay);
				}
			}
			rows.add(row);
		}
		String name = "学生信息-" + ".xlsx";
		String path = PathUtils.getFile("jh", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		// 合并单元格后的标题行，使用默认标题样式
		// 一次性写出内容，使用默认样式
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	@Override
	public void list() {
		JhStaff staff = getStaff();
		Long schoolId = getParaToLong("schoolId");
		Integer status = getParaToInt("status");
		Integer type = getParaToInt("type");
		Integer isVisited = getParaToInt("isVisited");
		Integer isFollowed = getParaToInt("isFollowed");

		String contractMode = getPara("contractMode");
		String channel = getPara("channel");
		Integer term = getParaToInt("term");
		Integer ccId = getParaToInt("ccId");
		Integer tmkId = getParaToInt("tmkId");
		Integer tuiguangId = getParaToInt("tuiguangId");
		Integer addStaffId = getParaToInt("addStaffId");

		/**
		 * 搜索电话/姓名
		 */
		String keyword = getPara("keyword");
		Kv kv = Kv.create();
		if (StrKit.notBlank(contractMode)) {
			setAttr("contractMode", contractMode);
			kv.set("contractMode", contractMode);
		}
		if (StrKit.notBlank(channel)) {
			String channelStr = "";
			String[] channelIds = channel.split(",");
			for (String string : channelIds) {
				Long channelId = Long.parseLong(string);
				JhChannel channelItem = JhChannel.dao.findById(channelId);
				if (channelItem == null) {
					continue;
				}
				channelStr = channelStr + channelItem.getName() + " ";
			}
			setAttr("channel", channel);
			kv.set("channel", "%" + channelStr + "%");
		}
		if (isVisited != null) {
			setAttr("isVisited", isVisited);
			kv.set("isVisited", isVisited);
		}
		if (isFollowed != null) {
			setAttr("isFollowed", isFollowed);
			kv.set("isFollowed", isFollowed);
		}
		if (term != null) {
			setAttr("term", term);
			kv.set("term", term);
		}
		if (ccId != null) {
			setAttr("ccId", ccId);
			kv.set("ccId", ccId);
		}
		if (addStaffId != null) {
			setAttr("addStaffId", addStaffId);
			kv.set("addStaffId", addStaffId);
		}
		if (tmkId != null) {
			setAttr("tmkId", tmkId);
			kv.set("tmkId", tmkId);
		}
		if (tuiguangId != null) {
			setAttr("tuiguangId", tuiguangId);
			kv.set("tuiguangId", tuiguangId);
		}
		if (StrKit.notBlank(keyword)) {
			kv.set("search", "%" + keyword + "%");
			kv.set("searchMobile", "%" + keyword + "%");
			setAttr("keyword", keyword);
		}
		if (status != null) {
			kv.set("status", status);
		}
		if (schoolId != null) {
			kv.set("schoolId", schoolId);
			setAttr("schoolId", schoolId);
		}
		String followType = getPara("followType");
		if (StrKit.notBlank(followType)) {
			kv.set("followType", followType);
			setAttr("followType", followType);
		}
		if (type != null) {
			kv.set("type", type);
			setAttr("type", type);
		}
		Integer isReview = getParaToInt("isReview");
		if (isReview != null) {
			kv.set("isReview", isReview);
			setAttr("isReview", isReview);
		}
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		if (StrKit.notBlank(startDate, endDate)) {
			kv.set("startDate", startDate);
			kv.set("endDate", endDate);
			setAttr("startDate", startDate);
			setAttr("endDate", endDate);
		}

		String contractStartDate = getPara("contractStartDate");
		String contractEndDate = getPara("contractEndDate");
		if (StrKit.notBlank(contractStartDate, contractEndDate)) {
			kv.set("contractStartDate", contractStartDate);
			kv.set("contractEndDate", contractEndDate);
			setAttr("contractStartDate", contractStartDate);
			setAttr("contractEndDate", contractEndDate);
		}

		String contractEndStartDate = getPara("contractEndStartDate");
		String contractEndEndDate = getPara("contractEndEndDate");
		if (StrKit.notBlank(contractEndStartDate, contractEndEndDate)) {
			kv.set("contractEndStartDate", contractEndStartDate);
			kv.set("contractEndEndDate", contractEndEndDate);
			setAttr("contractEndStartDate", contractEndStartDate);
			setAttr("contractEndEndDate", contractEndEndDate);
		}

		Integer dl = getParaToInt("dl", 0);
		if (dl.equals(1)) {
			download(kv);
			return;
		}

		List<JhSchool> schools = JhSchool.dao.findAll();
		setAttr("schools", schools);
		Page<Record> pages = JhStudent.dao.getStudents(staff, kv, getPage(), getPageSize());
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));

		List<JhStaff> ccs = JhStaff.dao.findByType(JhStaff.TYPE_CC);
		setAttr("ccs", ccs);
		List<JhStaff> tmks = JhStaff.dao.findByType(JhStaff.TYPE_TMK);
		setAttr("tmks", tmks);
		List<JhStaff> tuiguangs = JhStaff.dao.findByType(JhStaff.TYPE_TUIGUANG);
		setAttr("tuiguangs", tuiguangs);
		List<JhStaff> staffs = JhStaff.dao.findByTypes(JhStaff.TYPE_TUIGUANG, JhStaff.TYPE_TMK, JhStaff.TYPE_CC,
				JhStaff.TYPE_FRONT, JhStaff.TYPE_TA);
		setAttr("staffs", staffs);
		render("/jh/admin/student/index.html");
		if (!DEBUG) {
			ThreadUtil.safeSleep(2);
		}
	}

	/**
	 * 放弃了,不需要这个判断
	 * 
	 * @param date
	 * @return
	 */
	@Deprecated
	private boolean isDateToday(String date) {
		// String startDateStr = date;
		// if (date.length() > 10) {
		// Date start = DateUtils.dateFromString(date,
		// DateUtils.YYYYMMDD_HHMMSS);
		// startDateStr = DateUtil.format(start, DateUtils.YYYYMMDD);
		// }
		// if (startDateStr.equals(DateUtil.today())) {
		// return true;
		// }
		// return false;
		return true;
	}

	private void trimStudent(JhStudent student) {
		if (student == null) {
			return;
		}
		student.setName(trimString(student.getName()));
		student.setEnglishName(trimString(student.getEnglishName()));
		student.setMark(trimStringN(student.getMark()));
		student.setFinMark(trimStringN(student.getFinMark()));
		student.update();
	}

	public void tr() {
		Long studentId = getParaToLong("studentId");
		JhStudent student = JhStudent.dao.findById(studentId);
		trimStudent(student);
		renderSuccess();

	}

	/**
	 * 保存学生信息
	 */
	@Override
	public void submit() {
		Long studentId = getParaToLong("studentId");
		String name = getParaTrim("name");
		String englishName = getParaTrim("englishName");
		String birth = getPara("birth", DateUtil.today());
		String mobile = getPara("mobile");
		String idCard = getPara("idCard");
		String province = getPara("province");
		String city = getPara("city");
		String address = getPara("address");
		Long schoolId = getParaToLong("schoolId", getStaff().getSchoolId());
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String emergentContact = getPara("emergentContact");
		String contract = getPara("contract");
		String contractPrice = getPara("contractPrice");
		Integer contractType = getParaToInt("contractType");
		String contractStartDate = getPara("contractStartDate");
		String contractEndDate = getPara("contractEndDate");
		Integer type = getParaToInt("type", 0);
		// if (!type.equals(JhStudent.TYPE_CLIENT)) {
		// if (!isDateToday(contractStartDate)) {
		// renderMsg("合同日期错误");
		// return;
		// }
		// }
		String code = getPara("code");
		String lt = getPara("lt");
		String password = getPara("password");
		String demoTeacher = getPara("demoTeacher");
		String followType = getPara("followType");
		Long ccId = getParaToLong("ccId");
		Long tmkId = getParaToLong("tmkId");
		Long taId = getParaToLong("taId");
		Long tuiguangId = getParaToLong("tuiguangId");
		Integer isVIP = getParaToInt("isVIP");
		Integer isBlackList = getParaToInt("isBlackList");
		Integer age = getParaToInt("age", 0);
		Integer isDisable = getParaToInt("isDisable", 1);
		Integer isDemo = getParaToInt("isDemo");
		Integer isLeave = getParaToInt("isLeave");
		Integer canJoinCourse = getParaToInt("canJoinCourse");
		Integer canJoinNormal = getParaToInt("canJoinNormal");
		Integer status = getParaToInt("status", 0);
		Integer channlId = getParaToInt("channlId");
		Integer coreCourseLeft = getParaToInt("coreCourseLeft", 0);
		String tag = getPara("tag");
		Integer sex = getParaToInt("sex", 0);
		Integer isAvailable = getParaToInt("isAvailable", 1);
		String location = getPara("location");
		String channel = getPara("channel");
		String mark = getParaRelaceN("mark");
		Integer term = getParaToInt("term");

		String attachment = getPara("attachment");
		String degree = getPara("degree");

		String finMark = getParaRelaceN("finMark");

		String studentLevel = getPara("studentLevel");
		String allPay = getPara("allPay");
		String payMethod = getPara("payMethod");
		String firstPay = getPara("firstPay");
		String remainToPay = getPara("remainToPay");
		Integer payCount = getParaToInt("payCount");
		String courseFee = getPara("courseFee");

		String courseType = getPara("courseType", "");

		Integer isReview = getParaToInt("isReview");
		String contractMode = getPara("contractMode", "");
		String contractEndReason = getPara("contractEndReason");

		Date delayDateStart = getParaToDate("delayDateStart", null);
		Date delayDateEnd = getParaToDate("delayDateEnd", null);
		String delayReason = getPara("delayReason");
		Integer delayFee = getParaToInt("delayFee");

		String payPerTime = getPara("payPerTime");
		Integer payDay = getParaToInt("payDay");

		Date extraTimeStart = getParaToDate("extraTimeStart", null);
		Date extraTimeEnd = getParaToDate("extraTimeEnd", null);
		Integer extraFee = getParaToInt("extraFee");

		Date transferTimeStart = getParaToDate("transferTimeStart", null);
		Date transferTimeEnd = getParaToDate("transferTimeEnd", null);
		Integer transferFee = getParaToInt("transferFee");
		Integer isTransfer = getParaToInt("isTransfer", 0);

		Date offTimeStart = getParaToDate("offTimeStart", null);
		Date offTimeEnd = getParaToDate("offTimeEnd", null);
		Integer isOff = getParaToInt("isOff", 0);

		Integer isDelay = getParaToInt("isDelay", 0);

		boolean isNew = studentId == null;
		JhStudent info = isNew ? new JhStudent() : JhStudent.dao.findById(studentId);
		if (!isNew && info == null) {
			renderFailure(404, "student not found");
			return;
		}

		boolean isStudentCoreInfoChanged = false;
		boolean isStudentContractInfoChanged = false;

		if (studentId != null) {
			if (!info.getCoreCourseLeft().equals(coreCourseLeft)) {
				isStudentCoreInfoChanged = true;
			}
			if (info.isChanged("contractPrice", contractPrice)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("contract", contract)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("contractType", contractType)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("contractStartDate", contractStartDate)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("contractEndDate", contractEndDate)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("allPay", allPay)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("payMethod", payMethod)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("firstPay", firstPay)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("remainToPay", remainToPay)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("payCount", payCount)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("courseFee", courseFee)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("courseType", courseType)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("term", term)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("studentLevel", studentLevel)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("contractMode", contractMode)) {
				isStudentContractInfoChanged = true;
			} else if (info.isChanged("coreCourseLeft", coreCourseLeft)) {
				isStudentContractInfoChanged = true;
			}
		}

		info.setName(name);
		info.setEnglishName(englishName);
		info.setAge(age);
		info.setBirth(DateUtil.parse(birth, "yyyy-MM-dd"));
		info.setMobile(mobile);
		info.setIdCard(idCard);
		info.setProvince(province);
		info.setCity(city);
		info.setAddress(address);
		info.setSchoolId(schoolId);
		info.setStartTime(DateUtil.parse(startTime, "yyyy-MM-dd"));
		info.setEndTime(DateUtil.parse(endTime, "yyyy-MM-dd"));
		info.setEmergentContact(emergentContact);
		info.setContract(contract);
		info.setContractPrice(contractPrice);
		info.setContractType(contractType);
		info.setFollowType(followType);
		info.setDegree(degree);
		info.setLt(lt);

		info.setFinMark(finMark);
		info.setStudentLevel(studentLevel);
		info.setAllPay(allPay);
		info.setPayMethod(payMethod);
		info.setFirstPay(firstPay);
		info.setRemainToPay(remainToPay);
		info.setPayCount(payCount);
		info.setCourseFee(courseFee);

		info.setCourseType(courseType);
		info.setTerm(term);

		info.setContractMode(contractMode);
		info.setContractEndReason(contractEndReason);

		if (!type.equals(JhStudent.TYPE_CLIENT)) {
			if (StrKit.isBlank(tag)) {
				renderMsg("请选择等级");
				return;
			}
			if (info.getContractStartDate() == null) {
				if (!isDateToday(contractStartDate)) {
					renderMsg("合同日期错误");
					return;
				}

				if (StrKit.notBlank(contractStartDate)) {
					Date val = DateUtil.parse(contractStartDate, "yyyy-MM-dd");
					Date old = info.getContractStartDate();
					info.setContractStartDate(val);
					if (old != null) {
						if (val.getTime() != old.getTime()) {
							isStudentCoreInfoChanged = true;
							isStudentContractInfoChanged = true;
						}
					}
				}
				if (StrKit.notBlank(contractEndDate)) {
					Date val = DateUtil.parse(contractEndDate, "yyyy-MM-dd");
					Date old = info.getContractEndDate();
					info.setContractEndDate(val);
					if (old != null) {
						if (val.getTime() != old.getTime()) {
							isStudentCoreInfoChanged = true;
							isStudentContractInfoChanged = true;
						}
					}
				}
			} else {

				// String dt = DateUtils.dateFormat(info.getContractStartDate(),
				// DateUtils.YYYYMMDD);
				// if (!dt.equals(contractStartDate)) {
				// if (!isDateToday(contractStartDate)) {
				// renderMsg("合同日期错误");
				// return;
				// }
				// }
				// if (contractStartDate.length() > 10) {
				// } else {
				// if (!isDateToday(contractStartDate)) {
				// renderMsg("合同日期错误");
				// return;
				// }
				// }
			}
			if (StrKit.notBlank(contractStartDate)) {
				Date val = DateUtil.parse(contractStartDate, "yyyy-MM-dd");
				Date old = info.getContractStartDate();
				info.setContractStartDate(val);
				if (old != null) {
					if (val.getTime() != old.getTime()) {
						isStudentCoreInfoChanged = true;
						isStudentContractInfoChanged = true;
					}
				}
			}
			if (StrKit.notBlank(contractEndDate)) {
				Date val = DateUtil.parse(contractEndDate, "yyyy-MM-dd");
				Date old = info.getContractEndDate();
				info.setContractEndDate(val);
				if (old != null) {
					if (val.getTime() != old.getTime()) {
						isStudentCoreInfoChanged = true;
						isStudentContractInfoChanged = true;
					}
				}
			}
		}
		info.setCode(code);
		info.setPassword(password);
		info.setDemoTeacher(demoTeacher);
		info.setCcId(ccId);
		info.setTmkId(tmkId);
		info.setTaId(taId);
		info.setTuiguangId(tuiguangId);
		info.setIsVIP(isVIP);
		info.setIsBlackList(isBlackList);
		info.setIsDisable(isDisable);
		info.setIsDemo(isDemo);
		info.setIsLeave(isLeave);
		info.setCanJoinCourse(canJoinCourse);
		info.setCanJoinNormal(canJoinNormal);
		info.setType(type);
		info.setStatus(status);
		info.setChannelId(channlId);
		info.setCoreCourseLeft(coreCourseLeft);
		info.setTag(tag);
		info.setSex(sex);
		info.setIsAvailable(isAvailable);
		info.setLocation(location);
		info.setChannel(channel);
		info.setMark(mark);
		info.setAttachment(attachment);

		info.setDelayDateStart(delayDateStart);
		info.setDelayDateEnd(delayDateEnd);
		info.setDelayReason(delayReason);
		info.setDelayFee(delayFee);
		info.setPayPerTime(payPerTime);
		info.setPayDay(payDay);

		info.setIsOff(isOff);
		info.setOffTimeStart(offTimeStart);
		info.setOffTimeEnd(offTimeEnd);

		info.setIsTransfer(isTransfer);
		info.setTransferTimeStart(transferTimeStart);
		info.setTransferTimeEnd(transferTimeEnd);
		info.setTransferFee(transferFee);

		info.setExtraTimeStart(extraTimeStart);
		info.setExtraTimeEnd(extraTimeEnd);
		info.setExtraFee(extraFee);

		info.setIsDelay(isDelay);

		if (isReview != null) {
			info.setIsReview(isReview);
		}

		if (isStudentCoreInfoChanged) {
			/**
			 * 改变合同重要信息,学生禁止选课(放弃)
			 */
			// info.setIsDisable(1);

		}
		if (StrKit.notBlank(channel)) {
			String channelStr = "";
			String[] cids = channel.split(",");
			for (String string : cids) {
				Long channelId = Long.parseLong(string);
				JhChannel channelItem = JhChannel.dao.findById(channelId);
				if (channelItem == null) {
					continue;
				}
				channelStr = channelStr + channelItem.getName() + " ";
			}
			info.setChannelStr(channelStr);
		}

		/**
		 * 改变合同重要信息,状态更新为审核中
		 */
		if (isStudentContractInfoChanged) {
			if (JhStudent.TYPE_STUDENT.equals(info.getType())) {
				info.setIsReview(1);
				info.setReviewTime(new Date());
				info.setSubmitReviewStaffId(getStaff().getId());
			}
		}
		JhStaff staff = getStaff();
		if (JhStaff.TYPE_TUIGUANG.equals(staff.getType())) {
			if (info.getTuiguangId() == null) {
				info.setTuiguangId(staff.getId());
			}
		} else if (JhStaff.TYPE_TMK.equals(staff.getType())) {
			if (info.getTmkId() == null) {
				info.setTmkId(staff.getId());
			}
		} else if (JhStaff.TYPE_FRONT.equals(staff.getType())) {
			info.setIsVisited(1);
		}

		String path = PathUtils.getFile("jh", "temp", "excel", DateUtil.today(), "StudentModify.txt");
		FileWriter fileWriter = new FileWriter(path);
		String title = "=================={} {} {} {} \n";
		title = StrFormatter.format(title, DateUtil.now(), staff.getId(), staff.getName(),
				isStudentContractInfoChanged);
		fileWriter.append(title);
		if (studentId != null) {
			String oldData = JsonKit.toJson(JhStudent.dao.findById(studentId));
			fileWriter.append(oldData + "\n");
		}
		String data = JsonKit.toJson(info);
		fileWriter.append(data + "\n");
		fileWriter.append("==================\n");
		if (isNew) {
			info.setStaffId(staff.getId());
		}
		renderFailure();
		try {
			boolean flag = isNew ? info.save() : info.update();
			if (flag) {
				renderSuccess();
			}
		} catch (Exception e) {
			LogKit.warn("录入失败", e);
			renderMsg("提交失败,请检查录入信息(*手机号码是否已录入)");
		}

	}

	public void fix() {
		Long studentId = getParaToLong("studentId");
		JhStudent student = JhStudent.dao.findById(studentId);
		if (student == null) {
			renderFailure();
			return;
		}
		student.clearEmpty();
		student.update();
		renderSuccess();
	}

	@Before(SelfClientInterceptor.class)
	@Override
	public void info() {
		setReferer();
		Long studentId = getParaToLong("studentId");
		JhStudent student;
		if (studentId == null) {
			student = new JhStudent();
			student.setIsAvailable(1);
			setAttr("isNew", 1);
		} else {
			student = JhStudent.dao.findById(studentId);
			trimStudent(student);
			setAttr("isNew", 0);
		}
		List<JhSchool> schools = JhSchool.dao.findAll();
		// List<JhStaff> staffs = JhStaff.dao.findAll();
		// Kv kv = Kv.by("type", 3); // type:3 => cc
		// List<Record> ccStaffs = JhStaff.dao.getSubStaffs(null, kv, 1,
		// 1000).getList();
		String tags = PropKit.get("JH_COURSE_TAGS");
		String today = DateUtil.today();
		setInfoItem(JsonKit.toJson(student));
		setAttr("schools", jsonObject(schools));
		// setAttr("staffs", jsonObject(staffs));
		String ccStr = jsonObject(JhStaff.dao.findByType(JhStaff.TYPE_CC));
		setAttr("cc", ccStr);
		setAttr("tmk", jsonObject(JhStaff.dao.findByType(JhStaff.TYPE_TMK)));
		setAttr("tuiguang", jsonObject(JhStaff.dao.findByType(JhStaff.TYPE_TUIGUANG)));
		setAttr("ta", jsonObject(JhStaff.dao.findByType(JhStaff.TYPE_TA)));
		setAttr("tags", tags);
		setAttr("today", today);
		JhStaff staff = getStaff();
		setAttr("staffId", staff.getId());

		setAttr("isCC", JhStaff.TYPE_CC.equals(staff.getType()) ? 1 : 0);
		setAttr("isFin", JhStaff.TYPE_FIN.equals(staff.getType()) ? 1 : 0);
		setAttr("isTuiguang", JhStaff.TYPE_TUIGUANG.equals(staff.getType()) ? 1 : 0);
		setAttr("isTMK", JhStaff.TYPE_TMK.equals(staff.getType()) ? 1 : 0);
		setAttr("isFront", JhStaff.TYPE_FRONT.equals(staff.getType()) ? 1 : 0);
		render("/jh/admin/student/info.html");
	}

	/**
	 * 删除学生
	 */
	@Override
	public void delete() {
		Long studentId = getParaToLong("studentId");
		if (studentId == null) {
			renderMsg("删除失败");
			return;
		}
		JhStudent student = JhStudent.dao.findById(studentId);
		if (student == null) {
			renderMsg("删除失败");
			return;
		}
		student.delete();
		renderMsg("删除成功");
		// renderSuccess();
		// renderMsg("暂时未开放");
	}

	public void getStudents() {
		String search = getPara("search");
		String tag = getPara("tag");
		Kv kv = Kv.create();
		if (StrKit.notBlank(search)) {
			kv.set("search", "%" + search + "%");
			kv.set("searchMobile", search);
		}
		if (StrKit.notBlank(tag)) {
			kv.set("tag", tag);
		}
		Page<Record> pages = JhStudent.dao.getStudents(getStaff(), kv, getPage(), PAGE_SIZE);
		renderResult(pages);
	}

	private void downloadHistory(Kv kv) {
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHFindMyCourse", kv);
		List<Record> items = Db.use("jiahua").find(sqlPara);
		ArrayList<Map<String, Object>> rows = new ArrayList<>();
		for (Record record : items) {

			// record.set("date", DateUtil.format(record.get("startTime"),
			// "yyyy-MM-dd"));
			String date = DateUtil.format(record.get("startTime"), "yyyy-MM-dd");
			String time = DateUtil.format(record.get("startTime"), "HH:mm") + "~"
					+ DateUtil.format(record.get("endTime"), "HH:mm");

			// 名字，级别，电话，总金额，已交金额，总课时，已上课时，剩余课时，是否有续费，延期，休学与终止
			Map<String, Object> row = new LinkedHashMap<>();
			row.put("课程名称", record.getStr("name"));
			row.put("主题", record.getStr("topic"));
			row.put("日期", date);
			row.put("时间", time);
			row.put("教室", record.getStr("classroom"));
			row.put("校区", record.getStr("schoolName"));
			Integer isOnClass = record.getInt("isOnClass");
			row.put("是否已上过课", isOnClass.equals(1) ? "是" : "否");
			rows.add(row);
		}
		String name = "上课历史" + ".xlsx";
		String path = PathUtils.getFile("jh", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		// 合并单元格后的标题行，使用默认标题样式
		// 一次性写出内容，使用默认样式
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	public void courseHistory() {
		Long studentId = getParaToLong("studentId");
		String firstDayOfMonth = DateUtil.format(DateUtil.beginOfMonth(new Date()), "yyyy-MM-dd");
		String startDate = getPara("startDate", firstDayOfMonth);
		String endDate = getPara("endDate", DateUtil.today());
		if (StrKit.notBlank(startDate, endDate)) {
			startDate = startDate + " 00:00:00";
			endDate = endDate + " 23:59:59";
		}
		Long staffId = getParaToLong("staffId");
		Long courseId = getParaToLong("courseId");

		Kv kv = Kv.create();
		kv.set("studentId", studentId);
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);
		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (courseId != null) {
			setAttr("courseId", courseId);
			kv.set("courseId", courseId);
		}

		Integer dl = getParaToInt("dl", 0);
		if (dl.equals(1)) {
			downloadHistory(kv);
			return;
		}
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHFindMyCourse", kv);
		Page<Record> pages = Db.use("jiahua").paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (record.get("startTime") != null) {
				record.set("date", DateUtil.format(record.get("startTime"), "yyyy-MM-dd"));
				record.set("time", DateUtil.format(record.get("startTime"), "HH:mm") + "~"
						+ DateUtil.format(record.get("endTime"), "HH:mm"));
			}
		}
		setRainbow(pages);
		setItems(JSONUtil.toJsonStr(pages.getList()));
		setAttr("startDate", startDate);
		setAttr("endDate", endDate);
		setAttr("studentId", studentId);

		SqlPara durationPara = Db.use("jiahua").getSqlPara("JHStudentHistoryDuration", Kv.by("studentId", studentId));
		Record timeRecord = Db.use("jiahua").findFirst(durationPara);
		setAttr("courseTime", 0);
		if (timeRecord != null) {
			BigDecimal val = timeRecord.getBigDecimal("courseTime");
			if (val != null) {
				setAttr("courseTime", val.intValue());
			}
		}
		SqlPara teacherPara = Db.use("jiahua").getSqlPara("JHFindCourseTeachers");
		List<JhStaff> staffs = JhStaff.dao.find(teacherPara);
		setAttr("staffs", jsonObject(staffs));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", jsonObject(courses));
		render("/jh/admin/student/courseHistory.html");
	}

	// public void importFromExcel() {
	// ExcelReader reader = ExcelUtil.getReader("D:\\UserData\\Desktop\\1.xls");
	// List<List<Object>> readAll = reader.read();
	// for (List<Object> list : readAll) {
	// int index = readAll.indexOf(list);
	// System.out.println(index);
	// if (index == 0) {
	// continue;
	// }
	// if (list.get(3).toString().contains("签合同")) {
	// JhStudent student = new JhStudent();
	// if (list.get(1).toString().equals("九洲城校区")) {
	// student.setSchoolId(1L);
	// } else if (list.get(1).toString().equals("华发校区")) {
	// student.setSchoolId(2L);
	// }
	// student.setName(list.get(2).toString());
	// if (list.get(4).toString().equals("CB0")) {
	// student.setTag("CBI");
	// } else {
	// student.setTag(list.get(4).toString());
	// }
	// student.setMobile(list.get(5).toString());
	// if (list.get(6).toString().equals("男")) {
	// student.setSex(1);
	// } else if (list.get(6).toString().equals("女")) {
	// student.setSex(2);
	// }
	// student.setIdCard(list.get(7).toString());
	// student.setEnglishName(list.get(8).toString());
	// student.setAddress(list.get(10).toString());
	// student.setPassword("123456");
	// student.save();
	// }
	// }
	// renderSuccess();
	// }

	/**
	 * 批量修改CC
	 */
	public void changeCC() {
		String idStr = getPara("ids");
		Long ccId = getParaToLong("ccId");
		if (ccId == null) {
			renderMsg("修改失败");
			return;
		}
		String[] ids = idStr.split(",");
		for (String string : ids) {
			Long studentId = Long.parseLong(string);
			JhStudent student = JhStudent.dao.findById(studentId);
			student.setCcId(ccId);
			student.update();
		}
		// renderSuccess();
		renderMsg("修改成功");
	}

	/**
	 * 批量修改tmk
	 */
	public void changeTMK() {
		String idStr = getPara("ids");
		Long tmkId = getParaToLong("tmkId");
		if (tmkId == null) {
			renderMsg("修改失败");
			return;
		}
		String[] ids = idStr.split(",");
		for (String string : ids) {
			Long studentId = Long.parseLong(string);
			JhStudent student = JhStudent.dao.findById(studentId);
			student.setTmkId(tmkId);
			student.update();
		}
		// renderSuccess();
		renderMsg("修改成功");
	}

}
